<template>
    <div class="snow-page">
        <a-layout>
            <a-layout-sider style="min-width: 250px;">
                <div>
                    <h4 style="margin: 10px">企业列表

                        <a-input v-model="serachValue" style="width:180px" placeholder="关键字搜索" allow-clear />
                        <a-button type="primary" @click="InputEvent">
                            <template #icon>
                                <icon-search />
                            </template>
                        </a-button>
                    </h4>
                    <a-tree :data="treeNodes" :default-selected-keys="[25]" :field-names="{
                        key: 'id',
                        title: 'name',
                        children: 'children'
                    }" @select="clickTreeNode" style="margin-left: 5px;max-height: 100vh;overflow: auto;">
                        <template #title="{ name }">
                            <a-tooltip :content="name">
                                <div class="marquee">
                                    <icon-common />
                                    {{ name }}
                                </div>
                            </a-tooltip>
                        </template>
                    </a-tree>
                </div>
            </a-layout-sider>
            <a-layout>
                <a-layout-content>
                    <div class="snow-inner-page">
                        <a-form :model="formData.form" :label-col-props="{ span: 5 }" :wrapper-col-props="{ span: 18 }"
                            ref="formRef">
                            <a-row :gutter="16">
                                <a-col :span="6">
                                    <a-form-item field="name" label="名称">
                                        <a-input v-model="formData.form.name" placeholder="请输入名称" allow-clear />
                                    </a-form-item>
                                </a-col>
                                <a-col :span="6">
                                    <a-space>
                                        <a-button type="primary" @click="onSearch">
                                            <template #icon>
                                                <icon-search />
                                            </template>
                                            <template #default>查询</template>
                                        </a-button>
                                    </a-space>
                                </a-col>
                            </a-row>
                        </a-form>

                        <a-card v-for="(item, index) in sbLists" :key="index">
                            <template #title>
                                <div style="display: flex;"><img src="./sb.png" alt="" srcset=""
                                        style="width: 25px;height: 25px;padding-top: 10px;">
                                    <div style="margin-left: 5px;margin-top: 8px;">
                                        {{ item.name }}
                                    </div>
                                    <div style="margin-left: 50px;margin-top: 8px;">
                                        <a-tag color="arcoblue" v-if="item.data.iot_node_status == '在线'">{{
                                            item.data.iot_node_status
                                            }}</a-tag>
                                        <a-tag color="red" v-else>{{ item.data.iot_node_status }}</a-tag>
                                    </div>
                                    <div style="margin-left: 100px;margin-top: 8px;">
                                        网关号:{{ item.device_code }}
                                    </div>
                                </div>
                            </template>
                            <template #extra>
                                <a-link>设置参数</a-link>
                            </template>
                            <div>
                                <a-row>
                                    <a-col :span="12" v-for="(item2, index2) in item.iotSensorList" :key="index2">
                                        <div style="display: flex;margin-top: 20px;">
                                            <div>
                                                <img :src="item2.url" alt="" srcset=""
                                                    style="width: 45px;height: 45px;">
                                            </div>
                                            <div style="margin-left: 20px;">
                                                <div style="color: #000;">
                                                    {{ item2.name }}
                                                </div>
                                                <div style="margin-top: 10px;">
                                                    {{ timestampToTime(item2.register_time) }}
                                                </div>
                                            </div>
                                            <div
                                                style="margin-left: 20px;margin-top: 10px;color: #337ab7;font-size: 15px;width:140px;">
                                                {{ item2.sdata }}{{ item2.data.measure_unit_type }}
                                            </div>

                                            <div style="margin-left: 60px;margin-top: 10px;">
                                                <a href="javascript:void(0)"
                                                    @click="clickDetail(item.iotSensorList, item2.id)">详情<icon-double-right /></a>
                                            </div>
                                        </div>
                                    </a-col>

                                </a-row>
                            </div>
                        </a-card>


                    </div>
                </a-layout-content>
            </a-layout>
        </a-layout>
    </div>
</template>

<script setup lang="ts">
// import MenuItemIcon from "@/layout/components/Menu/menu-item-icon.vue";
// import dynamicRoutes from "@/mock/_data/system_menu";

import { getAllqiyeAPI } from "@/api/modules/qiye/index";
import { getsensorAPIList } from "@/api/modules/sensor2/index"
import { onMounted, ref } from "vue";
import { useUserInfoStore } from "@/store/modules/user-info";
const router = useRouter();
onMounted(() => {
    getInit();

});
const serachValue = ref("");
const treeNodes = ref([]);

function timestampToTime(timestamp) {
    let date = new Date(timestamp); // 如果时间戳是10位数，则需要乘以1000
    let Y = date.getFullYear() + '-';
    let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
    let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
    let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
    return Y + M + D + h + m + s;
}

function InputEvent() {
    if (serachValue.value) {
        treeNodes.value = [];
        let arr = [];
        for (let i = 0; i < optionData.value.length; i++) {
            if (optionData.value[i].name.includes(serachValue.value)) {
                arr.push(optionData.value[i])
            }
        }
        treeNodes.value = generateTreeNodes(arr);
    } else {
        let obj = {}
        getAllqiyeAPI(obj).then(res => {
            treeNodes.value = generateTreeNodes(res.data);
        })
    }
}

const timer = ref(null)
const optionData = ref([])
async function getInit() {
    let obj = {};
    let res = await getAllqiyeAPI(obj);
    if (res.status == 2) {
        treeNodes.value = generateTreeNodes(res.data);
        optionData.value = res.data;
        extraId.value = optionData.value[0].id
        init();
        timer.value = setInterval(function () {
            init();
        }, 30000)
    }
}




function generateTreeNodes(data) {
    const nodeMap = new Map();
    const rootNodes = [];

    // First pass: create nodes and store them in a map
    data.forEach(item => {
        const node = {
            id: item.id,
            name: item.name ? item.name : item.cq_company_short_name,
            children: [],
            data: item // Store all original data
        };
        nodeMap.set(item.cq_company_code, node);
    });

    // Second pass: build the tree structure
    data.forEach(item => {
        const node = nodeMap.get(item.cq_company_code);
        if (item.cq_parent_code === "0") {
            rootNodes.push(node);
        } else {
            const parentNode = nodeMap.get(item.cq_parent_code);
            if (parentNode) {
                parentNode.children.push(node);
            } else {
                console.warn(`Parent node ${item.cq_parent_code} not found for ${item.cq_company_code}`);
                rootNodes.push(node); // Add to root if parent not found
            }
        }
    });

    return rootNodes;
}

const extraId = ref(0)

function clickTreeNode(selectedKeys, extra) {
    extraId.value = selectedKeys[0]
    init();
    timer.value = setInterval(function () {
        init();
    }, 30000)
}

function getAllChildrenIds(node, idsArray) {
    // 把当前节点的 id 加入数组
    idsArray.push(node.id); // 如果有子节点，则递归处理
    if (node.children && node.children.length > 0) {
        node.children.forEach(child => {
            getAllChildrenIds(child, idsArray);
        });
    }
}


function clickDetail(list, id) {
    let stores = useUserInfoStore();
    stores.setDeviceListInfo(list);
    router.push({ path: "/jiankCenter/sbjkDetail", query: { id: id } });


}

const sbLists = ref([])

async function init() {
    let obj = {
        device_code: "",
        node_data_type: 0,
        scene_id: extraId.value
    }
    let res = await getsensorAPIList(obj);
    sbLists.value = [];
    if (res.status == 2) {
        sbLists.value = res.data;
    }
}


const formData = reactive({
    form: {
        name: "",
        scene_id: "",
        scene_ids: []
    },
    paged: 1,
    pageSize: 10
});

const formRef = ref();


async function onSearch() {
    init();
}




</script>

<style lang="scss">
.arco-modal-body {
    text-align: center !important;
}

.marquee {
    white-space: nowrap;
    /* 确保文本在一行内显示 */
    overflow: hidden;
    /* 隐藏溢出的内容 */
    text-overflow: ellipsis;
    /* 使用打点显示溢出的文本 */
    width: 100%;
    /* 设置宽度，根据需要调整 */
    max-width: 200px;
    /* 最大宽度，根据需要调整 */

    box-sizing: border-box;
    /* 防止宽度计算包含边框和内边距 */
}
</style>